//
//  TTNewHomeListView.m
//  TaoTuo
//
//  Created by LG on 2020/10/17.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTNewHomeListView.h"
#import "TTHomeListViewCell.h"
#import "TTHomeListModel.h"
#import "TTGoodsDetailViewController.h"
#import "TTHomeGridViewCell.h"

#import "TTGoodsDetailViewController.h"

static NSString *cellID = @"home_list_cell";

@interface TTNewHomeListView ()<UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UITableViewEmptyDataDelegate>

@property (nonatomic, copy) void(^scrollViewCallback)(UIScrollView *scrollView);
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UICollectionViewFlowLayout *gridLayout;   // 列表

@property (nonatomic, assign) BOOL notShowLoadingView; // 是否显示加载菊花

@end

@implementation TTNewHomeListView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.gridLayout = [[UICollectionViewFlowLayout alloc] init];
        self.gridLayout.sectionInset = UIEdgeInsetsMake(5, 10, 0, 10);
        self.gridLayout.minimumLineSpacing = 10;
        self.gridLayout.minimumInteritemSpacing = 10;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.gridLayout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = kSeparatorColor;
        [_collectionView registerClass:[TTHomeGridViewCell class] forCellWithReuseIdentifier:cellID];
        
        [self addSubview:_collectionView];
        
        [self refreshData];
        
        @weakify(self)
        self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            @strongify(self)
            [self loadMoreData];
        }];
        
        // 取出缓存数据展示
        self.dataArray = [LLPasswordManagerUtilies getDatasWithKey:saveHomeFirstListKey];
        [self.collectionView reloadData];
        
        
    }
        
    return self;
}

- (void)setSectionInsets:(UIEdgeInsets)sectionInsets
{
    _sectionInsets = sectionInsets;
    self.gridLayout.sectionInset = sectionInsets;
    [self.collectionView reloadData];
}

// 上拉加载
- (void)loadMoreData
{
    self.page++;
    self.notShowLoadingView = YES;
    [self getListData];
}

// 刷新数据
- (void)refreshData
{
    self.page = 1;
    self.notShowLoadingView = YES;
    [self getListData];
}

// 全部类型的列表数据
- (void)getListData
{
    NSMutableDictionary *dic = @{
                                 @"param.pageIndex" : @(self.page),
                                 @"param.pageSize" : @(40)
                                 }.mutableCopy;
    [self getAllTypeDataWithDic:dic];
    
}

- (void)getAllTypeDataWithDic:(NSMutableDictionary *)dic
{

    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:homeGoodsRecommendAsync_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        @strongify(self)
        [self handelDataWithArray:responseObject[@"Data"]];
        
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        @strongify(self)
        [self.collectionView.mj_footer endRefreshing];
        
    } showLoadingInView:nil];
}



- (void)handelDataWithArray:(NSArray *)arr
{
    @synchronized (self) {
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        for (NSDictionary *dic in arr) {
            TTHomeListModel *model = [TTHomeListModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        // 缓存全部类型的第一页的数据
        if (self.page == 1) {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                if (self.dataArray.count > 0) {
                    [LLPasswordManagerUtilies saveDatasWithKey:saveHomeFirstListKey object:self.dataArray];
                }
            });
        }
        
        if (arr.count < 40) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.collectionView.mj_footer endRefreshing];
        }
        
        [self.collectionView reloadData];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.collectionView.frame = self.bounds;
}

//- (void)emptyDataSetReloadData:(UITableView *)tableView
//{
//    [self getListData];
//}

#pragma mark - UITableViewDataSource, UITableViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTHomeListModel *model = self.dataArray[indexPath.row];
    TTHomeGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.model = model;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTHomeListModel *model = self.dataArray[indexPath.row];
    TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:model.StyleLibraryId model:model];
//    detailVC.styleLibraryId = model.StyleLibraryId;
    [self.viewController.navigationController pushViewController:detailVC animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.width - 30) * 0.5, 175 * kScale + 60);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (self.scrollViewCallback) {
        self.scrollViewCallback(scrollView);
    }
    if (scrollView.contentOffset.y == 0) {
        if (self.scrollToTopBlock) {
            self.scrollToTopBlock();
        }
    }
}

///停止拖拽可能还会滑动一段距离
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.scrollEnd) {
        self.scrollEnd(scrollView.contentOffset.y);
    }
}

///已经停止了
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.scrollEnd) {
        self.scrollEnd(scrollView.contentOffset.y);
    }
}


- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



@end
